#!/usr/bin/env bash

# Download manager for seedboxes. Requires the following setup:
#  - SSH Access, all files in a single directory, 
#  - Authenticated web access (i.e. user/password).
# 
# Presents a list of files (Folder download/removal not supported) in a certain directory on the remote server.
# Allows to select one or more file.
# For the selected files allow to download or delete (or delete after download)


SSH_USER="a_user"                                    # User name on ssh server
SSH_HOST="a_host"                                    # Server hostname
SSH_PATH="/home/username/foo/bar/"                   # Where the files are located
SSH_LIST_CMD="ls ${SSH_PATH}"                        # Command to list files on ssh server
# SSH_LIST_CMD="cd ${SSH_PATH} && find . -not -type d | sed -e 's/\.\///1'"

WEB_USER="webuser"                                   # User for web access
WEB_PASS="webuserpassword"                           # Password for web access
WEB_PRFX="http://example-server.com:8000/foo/bar/"   # Base URL for downloads

DEST_DIR="/Users/bridge/Desktop/"                    # Local directory where files are downloaded
DOWNLOAD_CMD="wget -q --progress=bar --continue --http-user=${WEB_USER} --http-password=${WEB_PASS}"; # Command for downloading

SSH_REMV_CMD="cd ${SSH_PATH} && rm"                  # Command for removing 

files=`ssh ${SSH_USER}@${SSH_HOST} ${SSH_LIST_CMD}`
if [[ $? != "0" ]]; then
	echo "Error downloading files list"
	exit 1;
fi

set -a farray;
count=0;
for afile in `echo $files | xargs`; do
	let 'count += 1'
	
	echo "[${count}] $afile"
	farray[${count}]=$afile;
done

for (( i = 1; i <= ${count}; i++ )); do
	echo  ">> ${farray[${i}]}";
done

echo "Enter selected files separarated by spaces:";
read SELECTION;

set -a dwnarray;
dwncount=0;
set -a delarray;
delcount=0;

for index in $SELECTION; do
	echo
	if [[ $index -lt 1 || $index -gt $count ]]; then
		echo "ERROR, invalid selection: $index";
		continue;
	fi
	
	echo "[${index}]: ${farray[${index}]}";

	echo "Download? [Y/n]"
	read ANSWER
	if [[ $ANSWER != "n" ]]; then
		let 'dwncount += 1';
		dwnarray[${dwncount}]=${farray[$index]};
	fi
	
	echo "Delete? [Y/n]"
	read ANSWER
	if [[ $ANSWER != "n" ]]; then
		let 'delcount += 1';
		delarray[${delcount}]=${farray[$index]};
	fi
done


echo;echo "Downloading:";
for (( i = 1; i <= ${dwncount}; i++ )); do
	echo "${dwnarray[$i]}"
done

echo "Deleting:";
for (( i = 1; i <= ${delcount}; i++ )); do
	echo "${delarray[$i]}"
done

echo "Continue?"
if [[ $ANSWER == "n" ]]; then
	exit 1;
fi

test -d ${DEST_DIR} && cd ${DEST_DIR};
if [[ $? != 0 ]]; then
	echo "ERROR: Failed to enter destination directory"
	exit 1;
fi

for (( i = 1; i <= ${dwncount}; i++ )); do
	echo "Downloading ${dwnarray[$i]}..."	
	${DOWNLOAD_CMD} "${WEB_PRFX}${dwnarray[$i]}"
done

echo "Deleting..."
ssh ${SSH_USER}@${SSH_HOST} "${SSH_REMV_CMD} ${delarray[*]}"


